package pt.fct.mpc.rfbul.test;

import java.util.List;

import pt.fct.mpc.rfbul.R;
import pt.fct.mpc.rfbul.database.MapperDatabaseAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ScannerActivity
	extends Activity
{
	private static final String TAG = null;
	private ProgressDialog progress_dialog;
	private Button button;
	
	private List<ScanResult> results;
	private Handler handler = new Handler();
	private OnClickListener listener_button =
		new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Log.d(TAG, "Clicking on view "+v.getId()
					+" with text = "+((Button) v).getText());
				switch (v.getId())
				{
					case R.id.layout_scan_button_start:
						doScan();
						break;
						
					case R.id.layout_scan_button_remove:
						removeGarbage();
						break;
				}
			}
		};
		
	private BroadcastReceiver receiver_results =
		new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			if (intent.getAction().equals(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
			{
				results = wifi_manager.getScanResults();
				
				if ((progress_dialog != null) 
					&& (progress_dialog.isShowing()))
				{
					progress_dialog.dismiss();
				}
				
//				if (wifi_lock != null)
//					if (wifi_lock.isHeld())
//						wifi_lock.release();
				
				handler.post(
					new Runnable()
					{
						@Override
						public void run()
						{
							doResultsHandling();
						}
					});
			}
		}
	};
	private WifiLock wifi_lock;
	private WifiManager wifi_manager;
	private ScannerActivity context;
	private Button button_garbage;
	private Button garbage_button;
		
		
		
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.rfbul_scan);
		
		this.context = this;
		
		this.button = (Button) findViewById(R.id.layout_scan_button_start);
		this.button.setOnClickListener(listener_button);
		
		this.button_garbage = 
			(Button) findViewById(R.id.layout_scan_button_remove);
		this.button_garbage.setOnClickListener(listener_button);
	}

	protected void removeGarbage()
	{
		String in_str = "";
		
		Toast.makeText(context, "removing garbage", Toast.LENGTH_SHORT);
		
		boolean first = true;
		for (ScanResult r : results)
		{
			if (r.SSID.equalsIgnoreCase("eduroam-guest"))
			{
				if (first)
					first = false;
				else
					in_str += ", ";
				
				in_str += "'"+r.BSSID+"'";
			}
		}
		
		Log.d(TAG, "removing macs: "+in_str);
		
		MapperDatabaseAdapter db = MapperDatabaseAdapter.getInstance(context);
		SQLiteDatabase conn = db.open();
		
		String remove_query =
			"delete from map where mac in ("+in_str+")";
		conn.rawQuery(remove_query, null);
		
		conn.close();
		
		this.garbage_button.setVisibility(View.GONE);
		Toast.makeText(context,	"Garbage removed!", Toast.LENGTH_SHORT);
	}

	protected void doScan()
	{
		this.wifi_manager = 
			(WifiManager) getSystemService(Context.WIFI_SERVICE);

		if (!wifi_manager.isWifiEnabled())
		{
			if (wifi_manager.getWifiState() != WifiManager.WIFI_STATE_ENABLING)
				wifi_manager.setWifiEnabled(true);
		}
//
//		this.wifi_lock = 
//			wifi_manager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, TAG);
//		this.wifi_lock.acquire();

		registerReceiver(receiver_results, 
			new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));


		this.progress_dialog = new ProgressDialog(this);
		this.progress_dialog.setMessage("Scanning...");
		this.progress_dialog.show();

		wifi_manager.startScan();
	}

	private void doResultsHandling()
	{
		ArrayAdapter<String> list_adapter =
			new ArrayAdapter<String>(context, R.layout.rfbul_list_item);
		
		boolean found_garbage = false;
		for (ScanResult r : results)
		{
			if (r.SSID.equalsIgnoreCase("eduroam-guest"))
				found_garbage = true;
			
			String str = r.SSID + "\n" + r.BSSID + " ("+r.level+")";
			list_adapter.add(str);
		}
		
		ListView lv = (ListView) findViewById(R.id.layout_scan_list_results);
		lv.setAdapter(list_adapter);
		
		if (found_garbage)
		{
			this.garbage_button = 
				(Button) findViewById(R.id.layout_scan_button_remove);
			this.garbage_button.setVisibility(View.VISIBLE);
		}
	}

}
